package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

/**
 * @author 虎哥
 */
@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    public List<CategoryDTO> queryCategoryOfParent(Long pid) {
        // 创建一个对象，对象中的非空参数，会成为sql的查询条件
        Category record = new Category();
        record.setParentId(pid);
        // 查询数据
        List<Category> list = categoryMapper.select(record);
        // 健壮性判断
        if (CollectionUtils.isEmpty(list)) {
            // 集合为空，没查到，返回404
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        // 转换dto
        return BeanHelper.copyWithCollection(list, CategoryDTO.class);
    }

    public List<CategoryDTO> queryByIds(List<Long> idList) {
        List<Category> list = categoryMapper.selectByIdList(idList);
        if (CollectionUtils.isEmpty(list)) {
            // 集合为空，没查到，返回404
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        // 转换dto
        return BeanHelper.copyWithCollection(list, CategoryDTO.class);
    }

    public List<CategoryDTO> queryAllLevels(Long id) {
        // 查询三级类目
        Category c3 = categoryMapper.selectByPrimaryKey(id);
        if (c3 == null) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        // 查询2级类目
        Category c2 = categoryMapper.selectByPrimaryKey(c3.getParentId());
        if (c2 == null) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        // 查询1级类目
        Category c1 = categoryMapper.selectByPrimaryKey(c2.getParentId());
        if (c1 == null) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        List<Category> list = Arrays.asList(c1, c2, c3);
        return BeanHelper.copyWithCollection(list, CategoryDTO.class);
    }
}
